package com.thread.PCProblem;


//测试:生产者,消费者模型-->利用缓冲区解决(管程法)
//生产者,产品,消费者,缓冲区
public class TestPc {
    public static void main(String[] args) {
        BufZone bufZone = new BufZone();

        new Productor(bufZone).start();
        new Consumer(bufZone).start();
    }

}

//生产者
class Productor extends Thread{
    BufZone bufZone;
    public Productor( BufZone bufZone){
        this.bufZone = bufZone;
    }

    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生产了第"+i+"件产品");
            bufZone.push(new Product(i));
        }
    }
}

//消费者
class Consumer extends Thread{
    BufZone bufZone;
    public Consumer( BufZone bufZone){
        this.bufZone = bufZone;
    }

    //消费


    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第"+bufZone.pop().id+"件产品");
        }
    }
}

//产品
class Product{
    int id;//产品编号

    public Product(int id) {
        this.id = id;
    }
}

//缓冲区
class BufZone {
    //容器大小
    Product[] container = new Product[10];
    //容器计数器
    int count = 0;

    //生产者生产
    public synchronized void push(Product p){
        //如果容器满了等待消费者消费
        if (count == container.length-1){
            //通知消费者消费,生产者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果没有忙就继续生产
        container[count] = p;
        count++;
        //可以通知消费者消费了
        this.notifyAll();

    }

    //消费者消费
    public synchronized Product pop(){
        //判断能否消费
        if (count==0){
            //等待生产者生产,消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果可以消费
        count--;
        Product p = container[count];//拿出并保存在p
        //通知生产者生产
        this.notifyAll();

        return p;
    }
}